package com.maben.udp.test004.client;

import com.maben.udp.test003.netty_client.MyClientHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;

import java.nio.charset.StandardCharsets;

/**
 * 普通客户端（可以和其他udp互通的）
 */
public class NettyClient {
    public static void main(String[] args) throws Exception {
        //负责装客户端的事件处理线程池
        EventLoopGroup clientWorker = new NioEventLoopGroup();
        try {
            //netty客户端引导启动器
            Bootstrap client = new Bootstrap();
            //把事件处理线程池添加进启动引导器
            client.group(clientWorker);
            //设置通道的建立方式,这里采用Nio的通道方式来建立请求连接
            client.channel(NioDatagramChannel.class);
            //此处添加客户端的通道处理器
            client.handler(new MyClientHandler());
            //客户端绑定端口并且开始发起连接请求
            ChannelFuture future = client.connect("127.0.0.1", 30003).sync();
            if (future.isSuccess()) {
                System.out.println("client started!！");
            }
            final Channel channel = future.channel();
            ByteBuf byteBuf = Unpooled.copiedBuffer("你好,服务器~".getBytes(StandardCharsets.UTF_8));
            channel.writeAndFlush(byteBuf);
            //关闭客户端
            channel.closeFuture();
            System.out.println("client is stopping!");
        } finally {
            //关闭事件处理组
            clientWorker.shutdownGracefully();
            System.out.println("client stopped!");
        }
    }
}
